<script lang="ts" setup>
import type { AiPromptTemplatesApi } from '#/api/ai/prompt/promptTemplates';

import { defineEmits, defineExpose, ref, watch } from 'vue';
import { useRoute } from 'vue-router';

import { Page } from '@vben/common-ui';

import { Button, message, Steps } from 'ant-design-vue';

import {
  createPromptTemplates,
  getPromptTemplates,
  updatePromptTemplates,
} from '#/api/ai/prompt/promptTemplates';

import VariablesInfo from '../../promptVariables/index.vue';
import BaseInfo from '../modules/base-info.vue';
import ContentInfo from '../modules/content-info.vue';
import EffectInfo from '../modules/effect-info.vue';
import PublishInfo from '../modules/publish-info.vue';
import UsedInfo from '../modules/used-info.vue';

const props = defineProps({
  hiddenBtn: { type: Boolean, default: false },
  template: { type: Object, default: () => ({}) },
});

const emit = defineEmits(['change', 'success']);

const route = useRoute();
/** 表单引用 */
const baseInfoRef = ref<InstanceType<typeof BaseInfo>>();
const contentInfoRef = ref<InstanceType<typeof ContentInfo>>();
const usedInfoRef = ref<InstanceType<typeof UsedInfo>>();
const effectInfoRef = ref<InstanceType<typeof EffectInfo>>();
const publishInfoRef = ref<InstanceType<typeof PublishInfo>>();
const variablesInfoRef = ref<InstanceType<typeof VariablesInfo>>();

const loading = ref(false);
const currentStep = ref(0);
const formData = ref<AiPromptTemplatesApi.PromptTemplates>({});
/** 步骤配置 */
const steps = [
  {
    title: '基本信息',
  },
  {
    title: '提示词内容',
  },
  {
    title: '变量设置',
  },
  {
    title: '使用说明',
  },
  {
    title: '效果展示',
  },
  {
    title: '发布设置',
  },
];
async function getInit() {
  const id = route.query.id as any;
  if (!id) {
    return;
  }
  loading.value = true;
  try {
    formData.value = await getPromptTemplates(id, '');
  } finally {
    loading.value = false;
  }
}
/** 下一步 */
function nextStep() {
  currentStep.value += 1;
}

/** 上一步 */
function prevStep() {
  if (currentStep.value > 0) {
    currentStep.value -= 1;
  }
}
/** 提交表单 */
async function submitForm() {
  // 表单验证
  const valid = await baseInfoRef.value?.validate();
  if (!valid) {
    currentStep.value = 0;
    stepChange(0);
    message.warn('保存失败，原因：基本信息表单校验失败请检查！！！');
    return;
  }
  const validContent = await contentInfoRef.value?.validate();
  if (!validContent) {
    currentStep.value = 1;
    stepChange(1);
    message.warn('保存失败，原因：提示词内容表单校验失败请检查！！！');
    return;
  }
  const validUsed = await usedInfoRef.value?.validate();
  if (!validUsed) {
    currentStep.value = 3;
    stepChange(3);
    message.warn('保存失败，原因：使用说明表单校验失败请检查！！！');
    return;
  }
  const validEffect = await effectInfoRef.value?.validate();
  if (!validEffect) {
    currentStep.value = 4;
    stepChange(4);
    message.warn('保存失败，原因：变量设置表单校验失败请检查！！！');
    return;
  }
  const validPublish = await publishInfoRef.value?.validate();
  if (!validPublish) {
    currentStep.value = 5;
    stepChange(5);
    message.warn('保存失败，原因：发布设置表单校验失败请检查！！！');
    return;
  }
  const hideLoading = message.loading({
    content: '保存中...',
  });
  try {
    // 拼接相关信息
    const baseInfo = await baseInfoRef.value?.getValues();
    const contentInfo = await contentInfoRef.value?.getValues();
    const usedInfo = await usedInfoRef.value?.getValues();
    const effectInfo = await effectInfoRef.value?.getValues();
    const variablesList = await variablesInfoRef.value?.getValues();
    const publishInfo = await publishInfoRef.value?.getValues();
    // 处理变量列表
    if (variablesList?.length) {
      variablesList.forEach((item: any) => {
        if (item.metadata && typeof item.metadata === 'string') {
          item.metadata = JSON.parse(item.metadata);
        }

        //  判断 id 是否为数字，不是则清空
        if (item.id && Number.isNaN(Number(item.id))) {
          item.id = null;
        }
      });
    }
    const data = {
      ...baseInfo,
      ...contentInfo,
      ...usedInfo,
      ...effectInfo,
      ...publishInfo,
      variablesList,
    };
    await (formData.value?.id
      ? updatePromptTemplates(data)
      : createPromptTemplates(data));
    emit('success');
    message.success('操作成功');
  } finally {
    hideLoading();
  }
}
/** 获取提示词模板详情 */
async function getPromptTemplate() {
  if (!formData.value.id) {
    return;
  }
  loading.value = true;
  try {
    const data = await getPromptTemplates(formData.value.id);
    formData.value = data || {};
  } finally {
    loading.value = false;
  }
}
function stepChange(index: number) {
  emit('change', index);
}
/** 动态更新表单值 */
watch(
  () => props.template,
  (val: any) => {
    formData.value = val || {};
    getPromptTemplate();
  },
  { deep: true, immediate: true },
);
/** 暴露出表单校验方法和表单值获取方法 */
defineExpose({
  submitForm,
  nextStep,
  prevStep,
  currentStep,
});
// 初始化
getInit();
</script>
<template>
  <Page auto-content-height v-loading="loading">
    <div>
      <Steps
        type="navigation"
        v-model:current="currentStep"
        class="rounded shadow-sm"
        @change="stepChange"
      >
        <Steps.Step
          v-for="(step, index) in steps"
          :key="index"
          :title="step.title"
        />
      </Steps>
      <div class="flex justify-center pt-6">
        <div style="width: 800px">
          <BaseInfo
            v-show="currentStep === 0"
            ref="baseInfoRef"
            :form-data="formData"
          />
        </div>
      </div>
      <div style="width: 100%">
        <ContentInfo
          v-show="currentStep === 1"
          ref="contentInfoRef"
          :form-data="formData"
        />
        <VariablesInfo
          v-show="currentStep === 2"
          ref="variablesInfoRef"
          :form-data="formData"
        />
      </div>
      <div class="flex justify-center">
        <div style="width: 800px">
          <UsedInfo
            v-show="currentStep === 3"
            ref="usedInfoRef"
            :form-data="formData"
          />

          <EffectInfo
            v-show="currentStep === 4"
            ref="effectInfoRef"
            :form-data="formData"
          />
          <PublishInfo
            v-show="currentStep === 5"
            ref="publishInfoRef"
            :form-data="formData"
          />
        </div>
      </div>
      <div v-if="!props.hiddenBtn" class="mt-4 flex justify-end space-x-2">
        <Button :disabled="currentStep === 0" @click="prevStep">上一步</Button>
        <Button :disabled="currentStep === steps.length - 1" @click="nextStep">
          下一步
        </Button>
        <Button type="primary" :loading="loading" @click="submitForm">
          保存
        </Button>
      </div>
    </div>
  </Page>
</template>
